package com.huitone.smspfm;

import java.io.FileInputStream;
import java.util.Arrays;

import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;

import com.bin.common.utils.ArrayUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.core.config.AppStaticConfigs;
import com.huitone.smspfm.core.listener.OutSideCommandsHandler;
import com.huitone.smspfm.core.listener.ShareMemoryCommandsListener;
import com.huitone.smspfm.exception.SimpleUncaughtExceptionHandler;
import com.huitone.smspfm.logger.ExtLogger;
import com.huitone.smspfm.task.CacheQueueProcessingTask;
import com.huitone.smspfm.task.GetPriListLengthTask;
import com.huitone.smspfm.task.ReloadConfigTimingTask;

/**   
* @Title Main.java 
* @Package com.huitone.smspfm 
* @Description 程序入口
* @author ozh   
* @date 2019年10月05日 
* @version V1.0   
*/
public class Main {
	
	static {
		try {
//			String path = Thread.currentThread().getContextClassLoader().getResource("log4j2.xml").getPath().substring(1).replace("/", "\\\\");
//			Configurator.initialize(null, new ConfigurationSource(new FileInputStream(path)));
//			String ShareMemoryFileCacheQueuePath = Thread.currentThread().getContextClassLoader().getResource("").getPath().substring(1).replace("/", "\\\\");
//			System.setProperty("ShareMemoryFileCacheQueue", ShareMemoryFileCacheQueuePath+"\\temp\\share.mm");
			Configurator.initialize(null, new ConfigurationSource(new FileInputStream(System.getProperty("log4j2.xml"))));
		} catch (Exception e) {
			System.out.println("初始化log4j2配置文件错误");
		}
	}
	
	private static final ExtLogger logger = ExtLogger.create(Main.class);
	
	private static ShareMemoryCommandsListener listener = null;
	
	private static GetPriListLengthTask getPriListLengthTask = null;
	
	private static ReloadConfigTimingTask reloadConfigTimingTask = null;
	
	private static CacheQueueProcessingTask cacheQueueProcessingTask = null;
	

	public static void main(String[] args) {
		
		// 定义全局的未捕捉异常处理类
		Thread.setDefaultUncaughtExceptionHandler(new SimpleUncaughtExceptionHandler());
		
		// 初始化全局参数
		AppStaticConfigs.init();
		
		// 构建外部命令监听器,监听start,stop,reload等命令
		listener = new ShareMemoryCommandsListener();
		listener.setHandler(new OutSideCommandsHandler() {

			@Override
			public void stop(String[] args) {
				logger.info("stop:" + Arrays.asList(args));
				
				if (ArrayUtils.isEmpty(args)) {
					
					stopCacheQueueService();
					stopOtherTasks();
					
					listener.stopListener();
					
				} else {
					
					String param = StringUtils.trim(args[0]);
					
					if (StringUtils.equalsIgnoreCase(param, "cacheQueueTasks")) {
						stopCacheQueueService();
					} else if (StringUtils.equals(param, "othertasks")) {
						stopOtherTasks();
					}
				}
			}

			@Override
			public void start(String[] args) {
				logger.info("start:" + Arrays.asList(args));
				
				if (ArrayUtils.isEmpty(args)) {
					
					startCacheQueueService();
					startOtherTasks();
					
				} else {
					
					String param = StringUtils.trim(args[0]);
					
					if (StringUtils.equalsIgnoreCase(param, "cacheQueueTasks")) {
						startCacheQueueService();
					} else if (StringUtils.equals(param, "othertasks")) {
						startOtherTasks();
					} 
				}
			}

			@Override
			public void reload(String[] args) {
				logger.info("reload:" + Arrays.asList(args));
				
				logger.info("短信平台预处理程序重新加载配置参数...");
				
				AppStaticConfigs.reload();
				
			}

			@Override
			public void handle(String[] args) {
				logger.info("handle:" + Arrays.asList(args));
			}
		});
		listener.startListener();
	}
	

	
	public static void startOtherTasks() {
		
		// 获取优先级队列长度
		if (getPriListLengthTask == null || !getPriListLengthTask.isAlive()) {
			getPriListLengthTask = new GetPriListLengthTask();
			getPriListLengthTask.start();
		}
		
		// 启动配置重载任务
		if (AppStaticConfigs.reloadConfigTimingOnOff) {
			if (reloadConfigTimingTask == null || !reloadConfigTimingTask.isAlive()) {
				reloadConfigTimingTask = new ReloadConfigTimingTask();
				reloadConfigTimingTask.start();
			}
		}
		
		
		
	}
	
	public static void stopOtherTasks() {
		
		if (getPriListLengthTask != null) {
			getPriListLengthTask.destroy();
			getPriListLengthTask = null;
		}
		
		if (reloadConfigTimingTask != null) {
			reloadConfigTimingTask.destroy();
			reloadConfigTimingTask = null;
		}
		
	}
	
	/**
	 * 启动缓存队列处理服务
	 */
	public static void startCacheQueueService() {
		
		logger.info("短信平台缓存队列处理服务正在启动...");
		
		if (cacheQueueProcessingTask == null || !cacheQueueProcessingTask.isAlive()) {
			cacheQueueProcessingTask = new CacheQueueProcessingTask();
			cacheQueueProcessingTask.start();
		}
    	
		logger.info("短信平台缓存队列处理服务启动完成");
	}
	
	/**
	 * 关闭缓存队列处理服务
	 */
	public static void stopCacheQueueService() {
		
		logger.info("短信平台缓存队列处理服务正在关闭...");
		
		if (cacheQueueProcessingTask != null) {
			cacheQueueProcessingTask.destroy();
			cacheQueueProcessingTask = null;
		} else {
			logger.info("短信平台缓存队列处理服务已经关闭");
		}
	}
}
